<template>
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="50%"
        :before-close="handleClose"
        >
        <el-row>
            <el-col :span="5" ref="rolename">角色名称</el-col>
            <el-col :span="18"> <el-input v-model="role.roleName"></el-input></el-col>
        </el-row>
        <el-row>
            <el-tree
                :data="allPermissions"
                show-checkbox
                node-key="permissionDesc"
                ref="tree"
                :props="defaultProps"
                >
            </el-tree>
        </el-row>
        <span slot="footer" class="dialog-footer">
            <el-button @click="$parent.dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="$parent.dialogVisible = false,updateRolePermissions()">确 定</el-button>
        </span>
    </el-dialog>

</template>
<script>
export default {
    props: ['role','dialogVisible'],
    data(){
        return {
            defaultProps: {
                children: 'children',
                label: 'permissionDesc',
            },
            refs: {}
        }
    },
    computed: {
        allPermissions(){
//      	console.log(this.$store.getters.allPermissions);
//          return this.$store.getters.allPermissions;  
			var Arr = [];
				var obj = this.$store.getters.allPermissions;
				for(var key in obj){
					Arr.push(obj[key])
				}
				return Arr;
        }
    },
    methods: {
        handleClose(){
            this.$parent.dialogVisible = false
        },
        updateRolePermissions(){
            var permissions = [];
            this.$refs.tree.getCheckedNodes().forEach((item)=>{
                permissions.push(item._id);
            })
            var params = {
                permissions: permissions,
                roleName: this.role.roleName,
                id: this.role._id
            }
            this.$http.post('/updateRoleInfo',params)
            .then((res)=>{
                this.$message({
                    message: res.success?res.message+'成功':res.message+'失败',
                    type: res.success?'success':'danger'
                })
            });
        }
    },
    watch: {
        role(newValue){
            setTimeout(()=>{
                var defaultPermission = [];
                this.$store.state.allPermissions.forEach((item)=>{
                    if(newValue.permissions.indexOf(item._id)!=-1){
                        defaultPermission.push(item);
                    }
                })
                this.$refs.tree.setCheckedNodes(defaultPermission);
            },0)
        }
    }
}
</script>
<style lang="scss" scoped>
    
</style>
